package com.relytosoft.mizar.media.alarm.services.api.impl;

import com.alibaba.fastjson.JSON;
import com.relytosoft.mizar.media.alarm.api.entity.Alarm;
import com.relytosoft.mizar.media.alarm.api.feign.AlarmFeignInService;
import com.relytosoft.mizar.media.alarm.api.pojo.dto.AlarmSaveDto;
import com.relytosoft.mizar.media.alarm.services.mapper.AlarmMapper;
import com.relytosoft.mizar.media.alarm.services.service.AlarmService;
import com.relytosoft.mizar.media.camera.api.feign.MultimediaFeignInService;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import com.relytosoft.mizar.media.common.entity.pojo.dto.AlarmDto;
import com.relytosoft.mizar.media.common.enums.ResourceTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.*;

import static com.relytosoft.mizar.media.common.constant.AlarmTypeConstants.COVER_VEHICLE_ALARM;

/**
 * @author Jierry
 * @version 2022/4/20.
 */
@Service
public class AlarmFeignInServiceImpl implements AlarmFeignInService {

    static ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(
                (int) (Runtime.getRuntime().availableProcessors() * 1.5),
                Runtime.getRuntime().availableProcessors() * 3,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MultimediaFeignInService multimediaFeignInService;
    @Autowired
    AlarmService alarmService;
    @Resource
    AlarmMapper alarmMapper;


    @Override
    public void handTaskAlarm(Alarm alarm) {
        try {
            CompletableFuture<Void> alarmFuture;
            if (Objects.equals(COVER_VEHICLE_ALARM, alarm.getAlarmTypeId())) {
                alarmFuture = CompletableFuture.runAsync(() -> alarmService.save(alarm));
            } else {
                alarmFuture = CompletableFuture.runAsync(() -> alarmMapper.saveDetailByDto(AlarmSaveDto.buildDto(alarm)));
            }
            CompletableFuture<Void> multimediaFuture = CompletableFuture.runAsync(() -> multimediaFeignInService.save(AlarmDto.buildAlarmDto(alarm), ResourceTypeEnum.ALARM_SNAPSHOT));
            CompletableFuture<Void> publishFuture = CompletableFuture.runAsync(() -> MqttOp.publish(MediaMqConstants.ALARM_TOPIC, JSON.toJSONString(alarm)));
            CompletableFuture.allOf(alarmFuture, multimediaFuture, publishFuture).join();
        } catch (Exception e) {
            log.info("保存报警记录异常--{}", alarm, e);
        }
    }


}
